<?php
class User_Model_ReportMapper{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('User_Model_DbTable_Report');
		}
		return $this->_dbTable;
	}
	

	
	public function save(User_Model_Report $report)
	{		
		try{
			$result=$this->getDbTable()->insert($report->toArray());
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		return $result;

	}
	

	
    public function findByUserid($id)
    {
		try{
			$select=$this->getDbTable()->select()->where("user_id=".$id);
			$result=$this->getDbTable()->fetchAll($select)->toArray();
			$sql=$select->__toString();
			if(count($result)){
				$result=new User_Model_Report($result[0]);
				return $result;
			}
			
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
    }
    
    public function countPassed(){
    	$select=$this->getDbTable()->select()->where("passed=1");
    	try{
    		$count=$this->getDbTable()->fetchAll($select)->count();
    		return $count;
    	}catch(Exception $e){
    		return Utils_SQLErrorMsg::formatException($e);
    	}
    }
    
    public function findAll($curPage=1,$perPage=30){
		$select=$this->getDbTable()->select()
							->limitPage($curPage, $perPage);
		$rows=$this->getDbTable()->getAdapter()->fetchOne("select count(*) from report");
		$data=array();
		try{
			$data=$this->getDbTable()->fetchAll($select)->toArray();
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		$response=new stdClass();
		$response->page=$curPage;
		$response->total=ceil($rows/$perPage);
		$response->records=(int)$rows;
		$response->rows=$data;
		return $response;
    }
    

}